<?php

namespace app\admin\controller\facrm\setting;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Cache;


/**
 * 数据同步
 * @icon fa fa-tags
 */
class Syndata extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['selectpage'];
    protected $key_user="syn_fa_user";
    protected $addon_config = array();
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("sourceList", $this->addon_config['source']);
        $this->request->filter(['strip_tags']);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $groupdata[0] = '选择归属组';
        $this->view->assign('groupdata', $groupdata);

    }

    /**
     * 用户列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            $this->model=new \addons\facrm\model\User();
            $settingModel = new \app\admin\model\facrm\Setting();
            $row = $settingModel->detail($this->key_user);
            $purpose=0;
            //判断是线索还是客户
            if ($row&&$row['values']){
                $values=json_decode($row['values'],true);
            }
            $with_name=[];
            if (isset($values['purpose'])&&$values['purpose']==2){
                //同步到线索
                $with_name='clues';
            }else{
                //同步到客户
                $with_name='customer';
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->with([$with_name=>function($q){
                $q->field('id,user_id');
                    }])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();


            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * FAST同步配置
     */
    public function synUserSet(){
        $this->model = new \app\admin\model\facrm\Setting();
        $row = $this->model->detail($this->key_user);
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try
                {
                    $params=array_merge($params,[
                        'values'=>json_encode($params['values'])
                    ]);
                    if (!$row){
                        $result = $this->model->allowField(true)->save($params);
                    }else{
                        Cache::rm($this->key_user);//删除缓存
                        $result = $row->allowField(true)->save($params);
                    }

                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        };
        if (!$row){
            //不存在就设置一些默认数据
            $row['values']="{\"source\":\"0\",\"group_id\":\"0\",\"owner_user_id\":\"\",\"needfollow\":\"0\",\"status\":\"0\"}";
        }
        $this->view->assign("row", $row);
        $this->view->assign('key',$this->key_user);
        return $this->view->fetch();

    }

    /**
     * 手动同步
     * @param null $ids 用户ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function synuser($ids=null){
        $user= \addons\facrm\model\User::get($ids);
        $result=\addons\facrm\library\Helper::synUser($user);
        if (!$result){
            $this->error("同步失败");
        }else{
            $this->success("同步成功");
        }

    }

}
